home *** CD-ROM | disk | FTP | other *** search
- Path: nntp.teleport.com!usenet
- From: GHouck <hksys@teleport.com>
- Newsgroups: comp.lang.c
- Subject: Re: Turbo C beginner: string question? Please help!
- Date: 4 Apr 1996 08:17:59 GMT
- Organization: systems hk
- Message-ID: <4k00jn$bsk@nadine.teleport.com>
- References: <Pine.SOL.3.91.960403054553.29446A-100000@jove.acs.unt.edu>
- NNTP-Posting-Host: ip-pdx09-29.teleport.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 1.22 (Windows; I; 32bit)
-
- Reynaldo Ortega <rortega@jove.acs.unt.edu> wrote:
- >
- >main()
- >{
- > char str[80];
- > printf("enter you name: ");
- > gets(str);
- > printf("hello %s", str);
- >}
- >QUESTION:
- > let's say I entered the name TARANTINO, and I wanted to compare each
- >single character in the string to display a count of occurences of
- >each character. How would I code this? Here is an example to clarify
- >what I am asking:
- Ray,
-
- First off, the mantra in this newsgroup is NEVER USE gets(), since it
- doesn't give you protection against a string being entered which is
- longer than your character array; however, it does in a pinch.
-
- I'd do something like this:
-
- char string[80];
- int chrCounts[356];
- int i;
-
- memset( chrCounts,0,sizeof(chrCounts) ); /* clear 256 counters */
- ...
- fgets( string,sizeof(string),stdin ); /* get your string */
- ...
- for( i=0; i<strlen(string); i++ ) /* seq thru chars, tallying each */
- ++chrCounts[(unsigned)string[i]];
- ...
- for( i=0; i<256; i++ ) /* for each non-zero count print it */
- if( chrCounts[i] > 0 ) /* i is each character as an index */
- printf( "%s has %d %c's",string,chrCounts[i],i );
- ...
-
- Yours, Geoff Houck
-
-
-